package com.lanhao.aot.aiui.entity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

import cn.hutool.http.HttpRequest;

public class DynamicEntityUpload {
	private static Logger LOG = LoggerFactory.getLogger(DynamicEntityUpload.class);
	private static final String UPLOAD_URL = "https://openapi.xfyun.cn/v2/aiui/entity/upload-resource";
	private static final String CHECK_URL = "https://openapi.xfyun.cn/v2/aiui/entity/check-resource";
	private static final String X_NONCE = "12";
	private static final String APPID = "";
	private static final String X_NAMESPACE = "IFLYTEK";
	private static final String ACCOUNTKEY = "";

	public void uploadDevEntity(String userId, List<DeviceAttr> devAttrList) {
		try {
			Map<String, String> header = this.buildHeader();
			String uploadBody = this.buildUploadBody(userId, devAttrList);
			String result = HttpRequest.post(UPLOAD_URL).addHeaders(header).body(uploadBody).execute().body();
			LOG.info("调用个性化实体上传url={},结果result={}", UPLOAD_URL, result);
			JSONObject uploadJo = JSON.parseObject(result);
			String code = uploadJo.getString("code");
			if ("00000".equals(code)) {
				// 上传资源数据后至少间隔3秒后再进行查看上传资源是否成功
				TimeUnit.SECONDS.sleep(3);
				String sid = uploadJo.getJSONObject("data").getString("sid");
				String checkBody = "sid=" + URLEncoder.encode(sid, "utf-8");
				String checkResult = HttpRequest.post(CHECK_URL).addHeaders(header).body(checkBody).execute().body();
				LOG.info("调用个性化实体上传校验url={},结果checkResult={}", CHECK_URL, checkResult);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Map<String, String> buildHeader() {
		String curTime = System.currentTimeMillis() / 1000L + "";
		String checkSum = DigestUtils.md5Hex(ACCOUNTKEY + X_NONCE + curTime);
		Map<String, String> header = new HashMap<String, String>();
		header.put("X-NameSpace", X_NAMESPACE);
		header.put("X-Nonce", X_NONCE);
		header.put("X-CurTime", curTime);
		header.put("X-CheckSum", checkSum);
		return header;
	}

	private String buildUploadBody(String userId, List<DeviceAttr> devAttrList) {
		try {
			String body = StringUtils.EMPTY;
			String resName = "IFLYTEK.smartH_deviceAlias";
			List<String> deviceDataList = Lists.newArrayList();
			for (DeviceAttr devAttr : devAttrList) {
				String aliasData = "{\"modifier\":\"" + devAttr.getModifier() + "\"," + "\"location\":{\"room\":\""
						+ devAttr.getRoom() + "\",\"zone\":\"" + devAttr.getZone() + "\",\"region\":\"\"},"
						+ "\"did\":\"" + devAttr.getDeviceId() + "\"," + "\"device\":\"" + devAttr.getService()
						+ "\",\"alias\":\"" + devAttr.getService() + "\"}";
				deviceDataList.add(aliasData);
			}
			String aliasDataReq = Joiner.on("\n").skipNulls().join(deviceDataList);
			Map<String, String> map = new HashMap<>(5);
			map.put("appid", APPID);
			map.put("id_name", "uid");
			map.put("id_value", "");
			map.put("res_name", resName);
			map.put("pers_param", "{\"auth_id\":\"" + userId + "\"}");
			map.put("data", new String(Base64.encodeBase64(aliasDataReq.getBytes("UTF-8"))));
			for (String key : map.keySet()) {
				body += key + "=" + URLEncoder.encode(map.get(key), "utf-8") + "&";
			}
			return body;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return StringUtils.EMPTY;
	}
}
